#!/bin/bash
HOME="/home"
MARIADB_NUMBER="10.5.6"
INSTALL_TARGET="/usr/local/mariadb"
MARIADB_FLOD="mariadb-$MARIADB_NUMBER-linux-x86_64"
MARIADB_TAR="$MARIADB_FLOD.tar.gz"
MARIADB_URL="https://mirrors.ustc.edu.cn/mariadb//mariadb-$MARIADB_NUMBER/bintar-linux-x86_64/$MARIADB_TAR"

#创建用户及用户组方法
function createUserGroupAndUser() {
    group=$1
    user=$2
    egrep "^$group" /etc/group >&/dev/null
    #创建用户组
    if [[ $? -ne 0 ]]; then
        groupadd $group
    fi
    #创建用户组下面的用户
    egrep "^$user" /etc/passwd >&/dev/null
    if [ $? -ne 0 ]; then
        useradd -r -s /sbin/nologin -g $group $user
    fi
}

rpm -q wget &>/dev/null
if [ $? -ne 0 ]; then
    yum install wget -y
fi

if [ ! -d "$HOME" ]; then
    mkdir $HOME
fi

cd "$HOME"
#下载镜像并解压Nginx源码包
if [ ! -f "$HOME/$MARIADB_URL" ]; then
    wget -c $MARIADB_URL && tar -zxf $MARIADB_TAR
fi

#创建用户组mariadb和用户mariadb
createUserGroupAndUser mariadb mariadb
#将解压后的文件夹放到安装的目录下
mv $MARIADB_FLOD $INSTALL_TARGET && cd $INSTALL_TARGET
#初始化数据库
mkdir -p ${INSTALL_TARGET}/data/mariadb && chown -R mariadb:mariadb ./ && ./scripts/mysql_install_db --basedir=$INSTALL_TARGET --user=mariadb --datadir=${INSTALL_TARGET}/data/mariadb
#开机自动启动
/bin/cp support-files/mysql.server /etc/init.d/mariadb
chmod +x /etc/init.d/mariadb
chkconfig –-add /etc/init.d/mariadb
chkconfig mariadb on

echo -e "\n\033[32m———————————————–\033[0m"
echo -e "\033[32mvim /etc/init.d/mariadb\033[0m"
echo -e "\033[32mbasedir=$INSTALL_TARGET\033[0m"
echo -e "\033[32mdatadir=$INSTALL_TARGET/data/mariadb\033[0m"
echo -e "\033[32m———————————————–\033[0m"
